package view.swing.tiles;

import static util.Constants.BLANK_SYMBOL;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import model.Letter;
import model.iview.ITile;

@SuppressWarnings("serial")
public class TilePanel extends JPanel {

    private static final Color BACK_COLOR = new Color(252, 247, 166);
    private static final Color TEXT_COLOR = new Color(20, 107, 83);
    private static final Color SELECTED_COLOR = BACK_COLOR.darker();
    private JLabel labelLettre;
    private JLabel labelScore;

    public TilePanel() {
        super();
    }

    public TilePanel(ITile tile) {
        this();
        GridBagLayout layout = new GridBagLayout();
        GridBagConstraints constraint = new GridBagConstraints();
        constraint.weighty = 1;
        constraint.weightx = 2;
        constraint.gridx = 0;
        constraint.gridy = 0;
        constraint.fill = GridBagConstraints.BOTH;

        setLayout(layout);
        labelLettre = new JLabel(tile.getLetter() != Letter.BLANK ? tile
                .getLetter().toString() : BLANK_SYMBOL);
        labelLettre.setForeground(TEXT_COLOR);
        Font f = labelLettre.getFont();
        labelLettre.setFont(f.deriveFont((float) 20));
        if (tile.isOldJoker()) {
            labelLettre.setForeground(Color.BLUE);
        }
        labelLettre.setHorizontalAlignment(SwingConstants.CENTER);
        labelLettre.setVerticalAlignment(SwingConstants.CENTER);
        add(labelLettre, constraint);

        constraint.gridx = 1;
        constraint.gridy = 0;
        constraint.weightx = 1;
        constraint.fill = GridBagConstraints.VERTICAL;

        labelScore = new JLabel(String.valueOf(tile.getScore()));
        labelScore.setForeground(TEXT_COLOR);
        Font f2 = labelScore.getFont();
        labelScore.setFont(f2.deriveFont((float) 10));
        labelScore.setVerticalAlignment(SwingConstants.BOTTOM);
        labelScore.setHorizontalAlignment(SwingConstants.RIGHT);
        add(labelScore, constraint);

        setBackground(BACK_COLOR);
        setBorder(BorderFactory.createLineBorder(Color.GRAY));
        
    }

    public void setNormal() {
        setBackground(BACK_COLOR);
    }

    public void setSelected() {
        setBackground(SELECTED_COLOR);
    }

    @Override
    protected void paintComponent(Graphics g) {
        
        Font f = labelLettre.getFont();
        Dimension size = getSize();
        float minSize = (float) (Math.min(size.height, size.width) / 1.6);
        if (Math.round(minSize) != f.getSize()) {
            labelLettre.setFont(f.deriveFont((float) (minSize)));
            labelScore.setFont(f.deriveFont((float) (minSize)/2));
        }
        
        super.paintComponent(g);
    }
}
